package com.qinyeit.serviceapp.utils;

import com.google.common.collect.Lists;
import com.qinyetech.springstage.core.lang.QyMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;


/**
 *
 * Created by Administrator on 2016/5/3.
 */
@Slf4j
public class Lang {

    public static String noPrintChar(String text){
        StringBuffer sb = new StringBuffer();
        for (char ch : text.toCharArray()){
            if(isChinese(ch) || CharUtils.isAsciiPrintable(ch)){
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    /**
     * 是否是中文字符
     * @param c 字符
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    /**
     * 是否是手机号
     * @param phone 手机号
     * @return
     */
    public static boolean isMobile(String phone){
        Matcher m = Pattern.compile("1\\d{10}", Pattern.MULTILINE + Pattern.DOTALL).matcher(phone);
        return m.matches();
    }

    public static String ip(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null){
            ip = "";
        }
        return ip;
    }


    public static Long[] str2LongArr(String ids) {
        String [] idStr = ids.split(",");
        return Stream.of(idStr).map(Long::valueOf).toArray(Long[]::new);
    }

    public static <T> QyMap page2Map(Page<T> page){
        QyMap map = QyMap.NEW();
        map.put("total", page.getTotalElements());
        map.put("totalPage", page.getTotalPages());
        map.put("size", page.getSize());
        map.put("page", page.getNumber());
        map.put("rows", page.getContent());
        return map;
    }


    public static <T> QyMap build(Page<T> page){
        QyMap rv = QyMap.NEW();
        rv.setv("list", page.getContent());

        QyMap pager = QyMap.NEW();
        pager.setv("recordCount", page.getTotalElements());
        pager.setv("pageCount", page.getTotalPages());
        pager.setv("pageNumber", page.getNumber());
        pager.setv("pageSize", page.getSize());
        pager.setv("isFirst", page.getNumber()==1);
        pager.setv("isLast", page.getNumber()==page.getTotalPages());
        pager.setv("offset", page.getSize()*(page.getNumber()-1));

        rv.setv("pager", pager);
        return rv;
    }

    /*public static BufferedImage qrcode(String context){
        QRCodeFormat format = QRCodeFormat.NEW();

        // 改变生成器格式的值
        format.setSize(400) // 设置图片大小
                .setEncode("GB18030") // 设置文字编码
                .setErrorCorrectionLevel('H') // 设置错误修正等级
                .setForeGroundColor("#2F4F4F") // 设置前景色
                .setBackGroundColor("#FFFFFF") // 设置背景色
                .setImageFormat("png") // 设置生成的图片格式
                .setMargin(0); // 设置图片空白区域, 单位 - 格（外填充）
//                .setIcon(new File("/PATH/TO/ICON_FILE")); // 设置 icon

        QRCode qrcode = QRCode.NEW(context, format);
        return qrcode.getQrcodeImage();
    }*/

   /* public static String image2Base64(BufferedImage image){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);

        try {
            ImageIO.write(image, "png", bos);
            bos.flush();
            bos.close();
            byte[] bImage = baos.toByteArray();
            return Coder.encryptBASE64(bImage).trim();
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessRunTimeException("生成二维码失败", 1000);
        }

    }*/
   public static List<QyMap> listMap2QyMap(List<Map<String, Object>> list){
       List<QyMap> maps = Lists.newArrayList();
       for (Map<String, Object> item : list) {
           maps.add(QyMap.WRAP(item));
       }
       return maps;
   }
    //获取下一个编号 例如 XA001 0001 033 X0A01B
    public static String getNextNo(String lastNo){
        String [] nums = lastNo.split("[^\\d]+");
        if(ArrayUtils.isEmpty(nums)){
            return "";
        }
        String tempNo = nums[nums.length-1];
        int num = Integer.valueOf(tempNo);
        int index = lastNo.lastIndexOf(tempNo);
        String startNo = lastNo.substring(0, index);
        String endNo = lastNo.substring(index+tempNo.length());
        if(tempNo.startsWith("0")){
            tempNo = StringUtils.leftPad(String.valueOf(num+1), tempNo.length(), "0");
        }else{
            tempNo = String.valueOf(num+1);
        }
        return startNo+tempNo+endNo;

    }
}
